package btb.core.tools;

import java.io.BufferedInputStream;
import java.io.FileInputStream;

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

/**
 * An adapted version of the MP3 player example shown in<br>
 * http://www.cs.princeton.edu/introcs/faq/mp3/MP3.java.html
 * @author mateamargo
 *
 */
public class Mp3Player {
	
	/**
	 * Plays the given file as a background process
	 * @param filename
	 * @param loop
	 * @throws ToolsException
	 */
	public static void play(final String filename, final boolean loop) throws ToolsException {
		try {
			FileInputStream fis = new FileInputStream(filename);
			BufferedInputStream bis = new BufferedInputStream(fis);
			
			final Player player = new Player(bis);
			
			Runnable r = new Runnable(){

				@Override
				public void run() {
					try {
						player.play();
						
						if(player.isComplete() && loop){
							play(filename, loop);
						}
					} catch (Throwable cause) {
						throw new RuntimeException(cause);
					}
				}
				
			};
			
			new Thread(r).start();
			
			
		} catch (Throwable cause) {
			throw new ToolsException("An error occurred playing an MP3 file", cause);
		}
	}
}
